using Assets.Scripts.Common;
using System.Collections.Generic;
using UnityEngine;

namespace Assets.Scripts.Controllers
{
    public class EconomyController : BaseController<EconomyController>
    {
        public event System.Action<CurrencyId, int> CurrencyBalanceChanged;

        private Dictionary<CurrencyId, int> _currencies = new Dictionary<CurrencyId, int>()
        {
            { CurrencyId.Dollars, 0 },
        };

        public int GetBalance(CurrencyId currency)
        {
            if (_currencies.ContainsKey(currency))
            {
                return _currencies[currency];
            }

            return default;
        }

        public void SetBalance(CurrencyId currency, int balance)
        {
            _currencies[currency] = balance;
        }

        public void GiveBonus(CurrencyId currencyId, int changeValue)
        {
            if (!_currencies.ContainsKey(currencyId))
            {
                _currencies.Add(currencyId, 0);
            }

            _currencies[currencyId] += changeValue;
            CurrencyBalanceChanged?.Invoke(currencyId,changeValue);
        }

        public void ChangeBalance(CurrencyId currencyId, int changeValue)
        {
            if (!_currencies.ContainsKey(currencyId))
            {
                _currencies.Add(currencyId, 0);
            }

            _currencies[currencyId] += changeValue;
            CurrencyBalanceChanged?.Invoke(currencyId, changeValue);

            PlayerPrefs.SetInt(currencyId.ToString(), _currencies[currencyId]);
        }

        public void ResetBalance(CurrencyId currencyId)
        {
            if (!_currencies.ContainsKey(currencyId))
            {
                return;
            }

            _currencies[currencyId] = 0;
        }

        public bool HasEnoughBalance(CurrencyId currencyId, int value)
            => GetBalance(currencyId) >= value;

        protected override void Awake()
        {
            base.Awake();

            ChangeBalance(CurrencyId.Dollars, PlayerPrefs.GetInt(CurrencyId.Dollars.ToString(), 0));
        }
    }
}
